<template>
    <div id="baiduMap" class="baiduMap"></div>
</template>

<script>

    export default {
        data () {
            return {
                map: null,
                toHistory: {
                    from: 'baidu'
                },
                timer: null // 保存刷新定时器
            }
        },
        methods: {
            getAddress (e, _this) {
                let pt = e.point
                // 点击点的坐标对象
                new BMap.Geocoder().getLocation(pt, function (rs) {
                    if (rs === undefined && rs === null)
                        return false
                    let addComp = rs.addressComponents
                    let addressDetail = addComp.province + addComp.city + addComp.district
                        + addComp.street + addComp.streetNumber
                    _this.$emit('sendAddrMsg', addressDetail)
                })
            },
            getEquip (data) {
                /*
                点击设备的话，未清除上一个设备的marker，此处有循环添加
                 */
                let json = $.extend(true, {}, data)
                this.createMark(json)
            },
            // 点击客户时，得到多个设备，显示maker调用此函数
            getEquips (equips) {
                this.map.clearOverlays() // 每次点击新客户，清空上一个客户的标记点
                this.clearTimer()
                if (equips.equips) {
                    equips.equips.forEach((item) => {
                        this.getEquip(item)
                    })
                }
            },
            trackInTime (equip) {
                this.setTimer(equip)
                if (equip.imei === undefined) {
                    return
                }
                this.$ajax
                    .equip
                    .queryEquipCoordinate(equip.imei)
                    .then((res) => {
                        let result = res.data
                        if (result.code === 200) {
                            if (result.result === undefined || result.result === null) {
                                return // 无结果
                            }
                            if (result.result.lat === undefined) {
                                return // 无坐标信息
                            }
                            new BMap.Convertor().translate([new BMap.Point(result.result.lng, result.result.lat)], 1, 5, (res) => {
                                if (res.status === 0) {
                                    let obj = JSON.parse(JSON.stringify(result.result))
                                    obj.lng = res.points[0].lng
                                    obj.lat = res.points[0].lat
                                    this.map.panTo(new BMap.Point(obj.lng, obj.lat))
                                    /**
                                     * 此处只是每次都会讲屏幕移至新的坐标点，但是在新位置却未生成新的marker
                                     * 注意：生成新marker后，上一个marker需去掉
                                     * 调用createMark(obj)方法
                                     */
                                }
                            })
                        } else if (result.code === 408) {
                            this.$store.commit('showAlert', {error: this.$msgDictionary.loginGetaway})
                            let timer = setTimeout(() => {
                                clearTimeout(timer)
                                $('#msgModal').modal('hide')
                                this.$router.push({path: '/login'})
                            }, 2000)
                        } else {
                            this.$store.commit('showAlert', {error: result.msg})
                        }
                    }, () => {
                        this.$store.commit('showAlert', {error: this.$msgDictionary.serviceException})
                    })
            },
            historyTrail (imei) {
                this.clearTimer()
                this.toHistory.imei = imei
                this.$router.push({path: '/history', query: {key: this.toHistory}})
            },
            equipInfo (imei) {
                this.$emit('showEquipInfo', imei)
            },
            createMark (val) {   //调用此函数创建标记点
                let src = val.online ? 'static/images/icon_1_online.png' : 'static/images/icon_1_offline.png'
                let pointArr = []
                if (val.lat === undefined) {
                    return // 无坐标信息
                }
                let point = new BMap.Point(val.lng, val.lat)
                let label = new BMap.Label(val.name, {offset: new BMap.Size(46, 10)}) // 创建标签
                label.setStyle({
                    color: '#344045',
                    border: 'none',
                    borderRight: '1px solid #344045',
                    fontSize: '12px',
                    height: '30px',
                    lineHeight: '10px',
                    fontFamily: '微软雅黑',
                    maxWidth: 'none',
                    padding: '10px',
                    background: 'transparent url(\'static/images/device_bg_small.png\') no-repeat'
                })
                let infoOpts = {
                    enableMessage: false,//设置允许信息窗发送短息
                    offset: {
                        width: 0, height: -50
                    }
                }
                let btnCss = 'height: 26px;border-radius: 13px;padding: 0 8px;border: 0;' +
                    'outline: none;font-size: 12px;color: #17D29C;background: #fff;border: 1px solid #17D29C; margin: 10px 0'
                let footCss = 'color: #17D29C;font-weight: bold;padding: 0 4px;color: #999'
                let msg = `
                     <div style="width: 100%;height: 178px">
                        <div style="width: 60%;float: left;padding: 8px 0 0 20px; color: #666;">
                            <p>${val.name}</p>
                            <p>${val.imei}</p>
                            <p>${val.online ? '在线' : '离线'}</p>
                            <p>电量${val.online ? val.electricity + '%' : ''}</p>
                            <p>定位于<br>${val.locationTime}</p>
                        </div>
                        <div style="width: 40%;float: right;">
                            <ul style="list-style: none;padding: 0">
                                <li><button type="button" style="${btnCss}" id="trackInTime">实时跟踪</button></li>
                                <li><button type="button" style="${btnCss}" id="historyTrail">历史轨迹</button></li>
                                <li><button type="button" style="${btnCss}" id="equipInfo">设备信息</button></li>
                            </ul>
                        </div>
                    </div>
                    <p style="text-align: left;width: 270px;color: #999;padding-left: 17px">
                        <span style="${footCss}">|</span>
                        撤防
                        <span style="${footCss}">|</span>
                        车门关
                        <span style="${footCss}">|</span>
                        主电断开
                        <span style="${footCss}">|</span>
                    </p>
                `
                let objE = document.createElement('div')
                objE.innerHTML = msg
                let InfoWindow = new BMap.InfoWindow(objE, infoOpts)
                InfoWindow.content.addEventListener('click', (e) => {
                    switch (e.target.id) {
                        case 'trackInTime':
                            this.trackInTime(val)
                            break
                        case 'historyTrail':
                            this.historyTrail(val.imei)
                            break
                        case 'equipInfo':
                            this.equipInfo(val)
                            break
                        default:
                            return
                    }
                })
                pointArr.push(point)
                new BMap.Convertor().translate(pointArr, 1, 5, (res) => {
                    if (res.status === 0) {
                        val.lng = res.points[0].lng
                        val.lat = res.points[0].lat
                        let point = new BMap.Point(val.lng, val.lat)
                        let marker = new BMap.Marker(point, {
                            icon: new BMap.Icon(src, new BMap.Size(41, 100))
                        })
                        this.map.addOverlay(marker) // 将标记点加到地图
                        marker.setLabel(label) // 标记点增加label标签
                        marker.setAnimation(BMAP_ANIMATION_DROP) // 标记点加载动画
                        this.map.openInfoWindow(InfoWindow, point) //开启信息窗口
                        marker.addEventListener('click', (e) => {
                            let p = e.target
                            this.map.openInfoWindow(InfoWindow, point) //开启信息窗口
                        })
                    }
                })
            },
            showEquipName (bool) {
                $('.BMap_Marker .BMapLabel').css('display', bool ? 'block' : 'none')
            },
            // 每隔15秒刷新一次
            setTimer (data) {
                let time = 15
                this.clearTimer()
                let cr = new BMap.CopyrightControl({anchor: BMAP_ANCHOR_TOP_LEFT, offset: new BMap.Size(150, 20)})
                this.map.addControl(cr)
                let content = `
                    <p style="background: #fff;padding: 5px"><span style="color: #f00">${time} </span>秒后刷新!</p>
                `
                cr.addCopyright({id: 1, content: content})
                this.timer = setInterval(() => {
                    time--
                    content = `
                        <p style="background: #fff;padding: 5px"><span style="color: #f00">${time} </span>秒后刷新!</p>
                    `
                    cr.addCopyright({id: 1, content: content})
                    if (time < 0) {
                        this.clearTimer()
                        this.map.removeControl(cr)
                        this.trackInTime(data)
                    }
                }, 1000)
            },
            clearTimer () {
                // 取出版权插件
                clearInterval(this.timer)
            }
        },
        destroyed () {
            this.clearTimer()
        },
        mounted () {
            // 百度地图API功能
            this.map = new BMap.Map('baiduMap')    // 创建Map实例
            this.map.centerAndZoom(new BMap.Point(113.956033, 22.560118), 14)  // 初始化地图,设置中心点坐标和地图级别
            //添加地图类型控件
            this.map.addControl(new BMap.MapTypeControl({
                mapTypes: [
                    BMAP_NORMAL_MAP,
                    BMAP_HYBRID_MAP
                ]
            }))
            this.map.addControl(new BMap.CityListControl({
                anchor: BMAP_ANCHOR_TOP_LEFT,
                offset: new BMap.Size(70, 20),
            }))
            this.map.addControl(new BMap.GeolocationControl())// 添加定位控件
            this.map.addControl(new BMap.ScaleControl())//比例尺控件
            this.map.addControl(new BMap.NavigationControl())//缩略地图控件
            this.map.addControl(new BMap.MapTypeControl())//地图类型控件
            this.map.setCurrentCity('深圳')         // 设置地图显示的城市 此项是必须设置的
            this.map.enableScrollWheelZoom(true)     //开启鼠标滚轮缩放
            let _this = this
            this.map.addEventListener('click', e => {
                _this.getAddress(e, _this)
            })
        },
    }
</script>

<style scoped>
    /* 地图引入 */
    html, body, .baiduMap {
        width: 100%;
        height: 100%;
        overflow: hidden;
        margin: 0;
    }

    .baiduMap {
        width: 100%;
        height: 93.6%;
    }

    .BMapLabel {
        max-width: none;
    }
</style>
